<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="tableForm" :inline="true" :model="listQuery">
        <el-row>
          <el-col :span="6">
            <el-form-item label="用户信息" prop="user_info">
              <el-input
                v-model="listQuery.user_info"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否首提" prop="is_first">
              <el-select v-model="listQuery.is_first" placeholder="请选择">
                <el-option label="是" :value="1" />
                <el-option label="否" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="支付宝账号" prop="account_number">
              <el-input
                v-model="listQuery.account_number"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="支付宝姓名" prop="account_name">
              <el-input
                v-model="listQuery.account_name"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="提现方式" prop="withdrawal_way">
              <el-select
                v-model="listQuery.withdrawal_way"
                placeholder="请选择"
              >
                <el-option label="支付宝" :value="1" />
                <el-option label="微信" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select v-model="listQuery.status" placeholder="请选择">
                <el-option label="申请中" :value="1" />
                <el-option label="已通过" :value="2" />
                <el-option label="已拒绝" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请时间" prop="settlement_time">
              <el-date-picker
                v-model="listQuery.created_at"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button @click="resetForm('tableForm')">重置</el-button>
            <el-button
              v-waves
              type="primary"
              icon="el-icon-search"
              @click="handleFilter"
            >
              {{ $t("table.search") }}
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-tabs v-model="listQuery.type" type="card" @tab-click="getList">
      <el-tab-pane label="全部" name="99" />
      <el-tab-pane label="待审核  " name="1" />
      <el-tab-pane label="已审核" name="2" />
      <el-tab-pane label="已拒绝" name="3" />
    </el-tabs>
    <div class="controlBox">
      <div class="totalBox">
        <div>待审核笔数：{{ totalNum.total_wait_num }}</div>
        <div>待审核总金额：{{ totalNum.total_wait_sum }}</div>
        <div>已审核笔数：{{ totalNum.total_success_num }}</div>
        <div>已提现总金额：{{ totalNum.total_success_sum }}</div>
        <div>提现手续费：{{ totalNum.total_handle_fee }}</div>
      </div>
      <div class="btnBox">
        <el-upload
          ref="upload"
          class="upload-btn"
          :action="baseUrl + '/withdrawal_import'"
          :headers="headers"
          name="pdf_file"
          :on-success="handleUploadSuccess"
          :show-file-list="false"
          :multiple="true"
          accept=".pdf"
        >
          <el-button class="fr" type="primary" size="mini"
            >上传已结算</el-button
          >
        </el-upload>
        <el-button
          class="fr"
          type="primary"
          size="mini"
          :disabled="!multipleSelection.length"
          @click="downSettlement()"
          >下载待结算</el-button
        >
        <el-button
          class="fr"
          type="success"
          size="mini"
          :disabled="!multipleSelection.length"
          @click="handleExamine(1)"
          >批量通过</el-button
        >
        <el-button
          class="fr"
          type="danger"
          size="mini"
          :disabled="!multipleSelection.length"
          @click="handleExamine(2)"
          >批量拒绝</el-button
        >
      </div>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        align="center"
        :selectable="selectable"
      />
      <el-table-column
        label="用户信息"
        prop="nickname"
        align="center"
        width="300"
      >
        <template slot-scope="{ row }">
          <div class="goodsInfo">
            <el-avatar
              :src="row.user.headimgurl"
              :size="50"
              fit="contain"
              @error="errorHandler"
            >
              <img
                src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
              />
            </el-avatar>
            <div class="textBox">
              <el-tooltip
                effect="dark"
                placement="top"
                :content="row.user.id + ''"
              >
                <div class="content">ID: {{ row.user.id }}</div>
              </el-tooltip>
              <el-tooltip
                effect="dark"
                placement="top"
                :content="row.user.nickname"
              >
                <div class="content">昵称：{{ row.user.nickname }}</div>
              </el-tooltip>
              <div class="content">手机号：{{ row.user.mobile }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="提现金额"
        prop="withdrawal_amount"
        align="center"
      />
      <el-table-column label="手续费" prop="handle_fee" align="center" />
      <el-table-column
        label="实际提现金额"
        prop="actual_amount"
        align="center"
        width="120"
      />
      <el-table-column
        label="实际转账金额"
        prop="transfer_amount"
        align="center"
        width="120"
      />
      <el-table-column label="提现方式" prop="withdrawal_way" align="center">
        <template slot-scope="{ row }">
          {{ row.withdrawal_way | withdrawalFilter }}
        </template>
      </el-table-column>
      <el-table-column
        label="支付宝账号/姓名"
        prop="account_number"
        align="center"
        width="170"
      >
        <template slot-scope="{ row }">
          {{ row.account_number || "-" }} / {{ row.account_name || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        label="申请时间"
        prop="created_at"
        align="center"
        width="170"
      />
      <el-table-column
        label="审核时间"
        prop="handle_time"
        align="center"
        width="170"
      />
      <el-table-column label="审核人" prop="handle_user" align="center" />
      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            v-if="row.status === 1"
            type="success"
            size="mini"
            @click="handleUpdate(row, 1)"
          >
            通过
          </el-button>
          <el-button
            v-if="row.status === 1"
            type="danger"
            size="mini"
            @click="handleUpdate(row, 2)"
          >
            拒绝
          </el-button>
          <span v-if="row.status !== 1"> {{ row.status | statusFilter }} </span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :visible.sync="dialogPvVisible" width="400px" title="拒绝原因">
      <el-input v-model="pvData" />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleRefuse">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="uploadVisible"
      title="上传明细"
      :close-on-click-modal="false"
    >
      <el-descriptions
        v-for="(item, key) in uploadList"
        :key="key"
        :title="item.file_name"
        :column="4"
        border
        style="margin-top: 40px"
      >
        <el-descriptions-item label="明细总数">
          {{ item.file_detail.total_num }}
        </el-descriptions-item>
        <el-descriptions-item label="明细总金额">
          {{ item.file_detail.total_amount }}
        </el-descriptions-item>
        <el-descriptions-item label="有效总数">
          {{ item.file_detail.effective_num }}
        </el-descriptions-item>
        <el-descriptions-item label="有效总金额">
          {{ item.file_detail.effective_amount }}
        </el-descriptions-item>
        <el-descriptions-item label="成功总数">
          {{ item.file_detail.success_num }}
        </el-descriptions-item>
        <el-descriptions-item label="失败总数">
          {{ item.file_detail.fail_num }}
        </el-descriptions-item>
        <el-descriptions-item label="无效总数">
          {{ item.file_detail.invalid_num }}
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            uploadVisible = false;
            uploadList = [];
          "
          >取消</el-button
        >
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchWithdrawalList,
  commissionAgain,
  withdrawalExamine,
  getSettleFetch,
  sendTransferCode,
} from "@/api/index";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Axios from "axios";
import { getToken } from "@/utils/auth";
export default {
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: "申请中",
        2: "已通过",
        3: "已拒绝",
      };
      return statusMap[status];
    },
    withdrawalFilter(status) {
      const statusMap = {
        1: "支付宝",
        2: "微信",
      };
      return statusMap[status];
    },
    typeFilter(status) {
      const statusMap = {
        1: "分享收益",
        2: "佣金收益",
      };
      return statusMap[status];
    },
    commissionFilter(status) {
      const statusMap = {
        1: "已结算",
        2: "未结算",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      uploadList: [],
      uploadVisible: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      headers: {
        "access-token": getToken(),
      },
      activeName: "first",
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10,
        type: "99",
      },
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" },
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        type: "",
        status: "published",
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "Edit",
        create: "Create",
      },
      dialogPvVisible: false,
      pvData: "",
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" },
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change",
          },
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" },
        ],
      },
      downloadLoading: false,
      totalNum: {
        total_wait_num: 0,
        total_wait_sum: 0,
        total_success_num: 0,
        total_success_sum: 0,
        total_handle_fee: 0,
      },
      order_id: 0,
      multipleSelection: [],
      changeId: "",
    };
  },
  created() {
    this.getList();
  },
  methods: {
    submitForm() {
      let code = [];
      for (let i of this.uploadList) {
        code.push(i.file_code);
      }
      code = code.toString();
      sendTransferCode({ file_codes: code }).then((res) => {
        this.$message({
          type: "success",
          message: "提交成功",
        });
        this.uploadList = [];
        this.uploadVisible = false;
        this.getList();
      });
    },
    handleUploadSuccess(res) {
      this.uploadVisible = true;
      if (res.code == 200) {
        this.uploadList.push(res.data);
      }
    },
    downSettlement() {
      const data = {
        ids:
          this.changeId ||
          this.multipleSelection.map((item) => item.id).join(","),
      };
      Axios({
        method: "post",
        url: process.env.VUE_APP_BASE_API + "/withdrawal_export",
        params: data,
        responseType: "blob",
        headers: { "access-token": getToken() },
      }).then((res) => {
        const blob = new Blob([res.data]);
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(blob); // 创建下载的链接
        downloadElement.href = href;
        downloadElement.download = "待结算明细.xls"; // 下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放掉blob对象
      });
    },
    handleRefuse() {
      withdrawalExamine({
        ids:
          this.changeId ||
          this.multipleSelection.map((item) => item.id).join(","),
        type: 2,
        reason: this.pvData,
      }).then(() => {
        this.$message({
          type: "success",
          message: "操作成功",
        });
        this.getList();
        this.pvData = "";
        this.dialogPvVisible = false;
      });
    },
    selectable(row) {
      if (row.status === 1) {
        return true;
      } else {
        return false;
      }
    },
    handleUpdate(row, type) {
      this.changeId = row.id + "";
      if (type === 1) {
        withdrawalExamine({
          ids: row.id + "",
          type,
        }).then(() => {
          this.$message({
            type: "success",
            message: "操作成功",
          });
          this.getList();
        });
      } else {
        this.pvData = "";
        this.dialogPvVisible = true;
      }
    },
    handleExamine(type) {
      this.changeId = "";
      if (type === 1) {
        withdrawalExamine({
          ids: this.multipleSelection.map((item) => item.id).join(","),
          type,
        }).then(() => {
          this.$message({
            type: "success",
            message: "操作成功",
          });
          this.getList();
        });
      } else {
        this.pvData = "";
        this.dialogPvVisible = true;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleAgain() {
      commissionAgain({ order_id: this.order_id }).then(() => {
        this.$message({
          type: "success",
          message: "操作成功",
        });
        this.dialogPvVisible = false;
      });
    },
    errorHandler() {
      return true;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getList() {
      const params = JSON.parse(JSON.stringify(this.listQuery));
      if (params.created_at && params.created_at.length) {
        params.created_at = params.created_at.join(",");
      } else {
        params.created_at = "";
      }
      this.listLoading = true;
      fetchWithdrawalList(params).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        Object.assign(this.totalNum, response.data);
        this.multipleSelection = [];
        this.listLoading = false;
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
  },
};
</script>
<style lang="scss" scoped>
.upload-btn {
  height: 28px;
  margin-right: 10px;
}
.goodsInfo {
  display: flex;
  align-items: center;
  .textBox {
    text-align: left;
    margin-left: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .content {
      width: 200px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.controlBox {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.totalBox {
  width: 100%;
  font-size: 14px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 20px;
}
.btnBox {
  display: flex;
  align-items: center;
}
</style>
